package com.example.demo.poi;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;

import java.util.List;
import java.util.Map;

/**
 * @author WangYX
 * @version 1.0.0
 * @date 2022/12/16 12:45
 */
public class EasyExcelDataListener<EasyExcelVo> implements ReadListener<EasyExcelVo> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 缓存的数据
     */
    private List<EasyExcelVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        ReadRowHolder readRowHolder = context.readRowHolder();
        if (readRowHolder.getRowIndex().equals(0)) {
            ReadCellData<?> readCellData = headMap.get(0);
            String stringValue = readCellData.getStringValue();
            ReadCellData<?> readCellData1 = headMap.get(1);
            String stringValue1 = readCellData1.getStringValue();
        } else {
            ReadCellData<?> readCellData = headMap.get(0);
            String stringValue = readCellData.getStringValue();
            ReadCellData<?> readCellData1 = headMap.get(1);
            String stringValue1 = readCellData1.getStringValue();
        }
    }


    @Override
    public void invoke(EasyExcelVo data, AnalysisContext context) {
        System.out.println(data.toString());
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        System.out.println("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        System.out.println(String.format("{}条数据，开始存储数据库！", cachedDataList.size()));
        System.out.println("存储数据库成功！");
    }
}
